const passport = require('koa-passport');
const LocalStrategy = require('passport-local');
const User = require('../dbs/models/user');
const {
  logger
} = require('../middleware/logger');
const md5 = require('md5')

//提交数据策略
passport.use(new LocalStrategy({
  usernameField: 'username',
  passwordField: 'password'
}, async function (username, password, done) {
  logger.info(`${username}==>${password}`);
  let where = {
    username
  };
  User.findOne(where, function (err, result) {
    if (result != null) {
      if (result.password == md5(password)) {
        return done(null, result, '登录成功')
      } else {
        return done(null, false, '密码错误')
      }
    } else {
      return done(null, false, '用户不存在')
    }
  }).catch(err => {
    logger.error(err.message);
    return done(null, false, {
      msg: err.message
    })
  });

}));

//序列化ctx.login()触发
passport.serializeUser(function (user, done) {
  //用户登录成功之后会把数据存到session当中
  done(null, user);
})

//反序列化（请求时，session中存在“passport：{user:1}”触发
passport.deserializeUser(function (id, done) {
  User.findById(id, function (err, user) {
    done(err, doPassword(user))
  })
});

//隐藏密码,相当于是去掉密码的用户信息保存在session里
function doPassword(user) {
  if (user) {
    user.password = ''
    return user
  } else {
    return null
  }
}

module.exports = passport;
